package com.smartsofa.adapter;

import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.smartsofa.R;
import com.smartsofa.main.DetailTopic;
import com.smartsofa.util.AsyncImageLoader;
import com.smartsofa.util.MyUtils;

public class TopicListAdapter extends BaseAdapter {
	
	protected int topicId;
	ViewHolder holder;
	private List<Map<String,Object>> mData;
	private LayoutInflater mInflater;
	private Context mContext;

	private String url;
	private Boolean flag;	
	private JSONObject json;
	private Boolean flag_image = false;
		
	//定义网络连接超时判定变量
	private boolean network_timeout=false;
	//异步加载图片
	private AsyncImageLoader imageLoader;

    protected final class ViewHolder{          
        public Button img_bt_praise;          
        public Button img_bt_comment;   
        public TextView tv_topic_praise;  
        public TextView tv_topic_comment;  
        public ImageView img_user2;
        public TextView tv_username;
        public TextView tv_topictime_value;
        public TextView tv_topic_content;
        public LinearLayout lay_list_item;
      }
	
    public TopicListAdapter(Context context, List<Map<String,Object>> data){      
    	this.mInflater = LayoutInflater.from(context); 
		this.mContext = context;
		this.mData = data;
		imageLoader = new AsyncImageLoader(context);
    } 

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		 return mData.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub			
		return mData.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub   
		if (convertView == null) {
			holder=new ViewHolder();     
            convertView = mInflater.inflate(R.layout.listview_topics, null);        
            
            holder.lay_list_item=(LinearLayout) convertView.findViewById(R.id.list_item);
            holder.img_bt_praise=(Button)convertView.findViewById(R.id.img_bt_praise);
            holder.img_bt_comment=(Button)convertView.findViewById(R.id.img_bt_comment);
            
            holder.tv_topic_praise=(TextView)convertView.findViewById(R.id.tv_topic_praise);
            holder.tv_topic_comment=(TextView)convertView.findViewById(R.id.tv_topic_comment);
            holder.img_user2=(ImageView)convertView.findViewById(R.id.topiclist_userimg);
            holder.tv_username=(TextView)convertView.findViewById(R.id.tv_username);
            holder.tv_topictime_value=(TextView)convertView.findViewById(R.id.tv_topictime_value);
            holder.tv_topic_content=(TextView)convertView.findViewById(R.id.tv_topic_content);
            
            convertView.setTag(holder); 
        
		}else{
			holder = (ViewHolder) convertView.getTag();
		}
        holder.tv_username.setText(mData.get(position).get("userName").toString());
        holder.tv_topic_praise.setText(mData.get(position).get("praiseNum").toString());
        holder.tv_topic_comment.setText(mData.get(position).get("commentNum").toString());
        String topic_content=mData.get(position).get("topicContent").toString();
        if(topic_content.length()<40){
        	holder.tv_topic_content.setText(topic_content);
        }
        else{
        	holder.tv_topic_content.setText(topic_content.substring(0, 39)+"...");
        }
        holder.tv_topictime_value.setText(mData.get(position).get("publicTime").toString());   
        
        //获取帖子ID
        topicId=(Integer) mData.get(position).get("topicId");
        /**
         * 设置listview的item监听
         */
        holder.lay_list_item.setOnClickListener(new ClickDetailTopicListener(topicId));                                                  
        holder.img_bt_praise.setOnClickListener(new OnClickListener(){
        	
            public void onClick(View arg0) {  
                // TODO Auto-generated method stub                            	
                Thread praise_thread=new Thread(new praiseNetThread(topicId));
                praise_thread.start();
            }
        });

    	// 预设一个图片
 		holder.img_user2.setImageResource(R.drawable.user_img2);
 		if (mData.get(position).containsKey("userImg")&&!("").equals(mData.get(position).get("userImg"))) {
 			final String imgUrl = (String) mData.get(position).get("userImg");
 			System.out.println("imgUrl..........."+imgUrl);
 			// 给 ImageView 设置一个 tag
 			holder.img_user2.setTag(imgUrl);
 			if (!TextUtils.isEmpty(imgUrl)) {
 				Bitmap bitmap = imageLoader.loadImage(holder.img_user2, imgUrl);
 				if (bitmap != null) {
 					holder.img_user2.setImageBitmap(bitmap);
 				}
 			}
 		}
        
        return convertView;        
        }
	
	class ClickDetailTopicListener implements OnClickListener{
		private int topicid;
		public ClickDetailTopicListener(int topicId){
			this.topicid=topicId;
		}
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			Intent intent=new Intent();
			Bundle bundle=new Bundle();
			bundle.putInt("topicId", topicid);
			intent.putExtras(bundle);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
			intent.setClass(mContext, DetailTopic.class);
			mContext.startActivity(intent);
		}
		
	}
	
	/**
	 * 点赞线程
	 * @author YuHuan
	 *
	 */
	class praiseNetThread implements Runnable{
		int topicId;
		public praiseNetThread(int topicId){
			this.topicId=topicId;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {			
				url=MyUtils.getUrl()+"topic_praiseTopic?topicid="+topicId;
				HttpGet request = new HttpGet(url);		
				//以下三行为连接服务器超时判断，如果超时将不执行以下所有代码
			   BasicHttpParams httpParams = new BasicHttpParams();
			   HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
		       HttpClient httpClient = new DefaultHttpClient(httpParams);
		       HttpResponse httpResponse = httpClient.execute(request);							       
		       	
		      if (httpResponse.getStatusLine().getStatusCode() == 200) {
		    	network_timeout=true;
		        String jsonString = EntityUtils.toString(httpResponse.getEntity());
		        json = new JSONObject(jsonString);
		        flag=(Boolean) json.get("success");			        				      		       
		      }
		      }catch (Exception e) {
		        	 e.printStackTrace();
		      }
			Message msg = praise_handler.obtainMessage();
			if(network_timeout){
				if (flag) {				
					msg.what = 1;									
				}else{
					msg.what = 2;			
				}
			}			
			else{
				msg.what = 3;						
			}
			praise_handler.sendMessage(msg);			
		}	
	}
	Handler praise_handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {		
			case 1:
				Toast.makeText(mContext.getApplicationContext(), "点赞成功！", Toast.LENGTH_SHORT).show();
				
				break;
			case 2:
				Toast.makeText(mContext.getApplicationContext(), "操作失败，请稍后再试！", Toast.LENGTH_SHORT).show();
				break;
			case 3:
				Toast.makeText(mContext.getApplicationContext(), "网络连接超时！", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};	
}